// pages/find/find.js
let http = require('../../utils/api.js');
let domain = require('../../utils/api.js');
const md5 = require('../../libs/md5.js')
import {
    myHttps,
    login
} from '../../utils/util.js';
Page({

    /**
     * 页面的初始数据
     */
    data: {
        channelId:0,//频道id默认0
        ballBottom: 0,
        ballRight: '50%',
        screenHeight: 0,
        screenWidth: 0,
        topLooks: '0',
        cid: '',
        id: 0,
        show: false, //二维码弹窗
        searchKeyword: '',
        iconsize: 12,
        isFocus: '',
        findList: [], //发现页面列表数据
        findNav: '', //findnav
        res: '', //请求回来的所有数据
        code: '',
        Isshow:false,
        first: false, //是否授权的登录的弹框
        userInfo: '', //用户信息
        loginType: '', //如果拒绝授权 拿到得状态
        nologin: '', //判断是否授权登陆得字段
        first: '',
        userInfo: '', //用户详情
        userId: '', //用户id
        hiddenLoading: false,
        size: 10, //页容量
        page: 1, //当前页
        ids: 0,
        indexs: '',
        userId: '', //用户id
        image: '../../images/erweima.png',
        winHeight: "", //窗口高度
        height:'',
        currentIndex: 0, //预设当前项的值
        scrollLeft: 0, //tab标题的滚动条位置
        refreshTime: '', // 刷新的时间 
        contentlist: [], // 列表显示的数据源
        allPages: '', // 总页数
        // currentPage: 1, // 当前页数  默认是1
        refreshTime: '', // 刷新的时间 
        channelList: [],//媒体列表
        domain:'',//ip
        hideHeader: true,
        hideBottom: true,
        refreshTime: '', // 刷新的时间 
        loadMoreData: '加载更多……' ,
        findListLength:'',
        findListAllLength:'',
        Bheight:0,//频道下面的高度
    },
    // 点更多 跳转到媒体列表
    gomediaList(e) {
        let id = e.currentTarget.dataset.channel.id
        let channel = e.currentTarget.dataset.channel.title
        // console.log(id)
        // console.log(channel)
        wx.navigateTo({
            url: '../mediaList/mediaList?id=' + id + '&channel=' + channel,
            success: function (res) { },
            fail: function (res) { },
            complete: function (res) { },
        })
    },
   
    // 除了全部以外 频道下面的列表接口
    channelList(id,isxiala) {
        let url = http.api.channel + id + '?size=' + this.data.size + '&page=' + this.data.page;
        myHttps({
            url: url,
            method: "GET",
        }).then(res => {
            if (res.code == 1) {
                if (res.data.content.length<6){
                    var Isshow=true
                }else{
                    var Isshow = false
                }
                
                if (isxiala) {
                    this.data.findList = res.data.content
                }else {
                    for (var i = 0; i < res.data.content.length; i++) {
                        this.data.findList.push(res.data.content[i])
                    }
                }
                this.setData({
                    Isshow: Isshow,
                    findList: this.data.findList,
                    hiddenLoading: true,
                    hideHeader:true,
                    findListLength: this.data.findList.length
                })
                if (this.data.findList.length > 7) {
                    this.setData({
                        Bheight:0
                    })
                } else if (this.data.findList.length == 1) {
                    this.setData({
                        Bheight:350
                    })
                } else if (this.data.findList.length == 2) {
                    this.setData({
                        Bheight: 300
                    })
                } else if (this.data.findList.length == 3) {
                    this.setData({
                        Bheight: 250
                    })
                } else if (this.data.findList.length == 4) {
                    this.setData({
                        Bheight: 200
                    })
                } else if (this.data.findList.length == 5) {
                    this.setData({
                        Bheight: 150
                    })
                } else if (this.data.findList.length == 6) {
                    this.setData({
                        Bheight: 100
                    })
                }
            }
        }).catch(err => {})
    },
    // 请求所有数据列表
    getMessage(size, page, isxiala) {
        let url = http.api.find + '?size=' + size + '&page=' + page
        myHttps({
            url: url,
            method: "GET",
        }).then(res => {
            if (res.code == 1) {
                if (isxiala) {
                    this.data.findList = res.data.content;
                } else {
                    for (var i = 0; i < res.data.content.length; i++) {
                        this.data.findList.push(res.data.content[i])
                    }
                }

                // console.log(this.data.findList.length+ '111')
                this.setData({
                    allPages: res.data._meta.last_page,
                    findList: this.data.findList,
                    hiddenLoading: true,
                    hideHeader: true,
                    findListAllLength: this.data.findList.length
                })
                if (this.data.findList.length > 7) {
                    this.setData({
                        Bheight:0
                    })
                }
            }
        }).catch(err => { })
    },
    // 滚动切换标签样式
    switchTab: function (e) {
        // console.log(e)
        let index = e.detail.current
        var id = this.data.findNav[index].id
        // console.log(id)
        this.setData({
            channelList: [],
            findList: [],
            page: 1,
            ids: id,
            currentIndex: index
        })
        console.log(this.data.currentIndex+':')
        this.checkCor();
        this.mediasChannel(id);// 获取媒体列表接口
        // 走搜索接口
        if (id == 0) {
            this.getMessage(this.data.size, this.data.page); //首次进入页面需要请求    
        } else {
            this.channelList(id)
        }
    },
    // 点击标题切换当前页时改变样式
    swichNav: function (e) {
        console.log(e)
        var cur = e.target.dataset.current;
        let index = e.currentTarget.dataset.index
        let id = e.currentTarget.dataset.id
        this.setData({
            channelList: [],
            findList: [],
            page: 1,
            ids: id,
            indexs: index,
            id: index, //只是标识颜色样式
            currentIndex: index
        })
        // console.log(this.data.currentIndex)
        // this.mediasChannel(id);// 获取媒体列表接口
        // // 走搜索接口
        // if (id == 0) {
        //     this.getMessage(this.data.size, this.data.page); //首次进入页面需要请求   
        // } else {
        //     this.channelList(id)
        // }
    },
    //判断当前滚动超过一屏时，设置tab标题滚动条。
    checkCor: function () {
        if (this.data.currentIndex > 4) {
            this.setData({
                scrollLeft: 300
            })
        } else {
            this.setData({
                scrollLeft: 0
            })
        }
    },
    // 获取媒体列表接口
    mediasChannel(channelId) {
        let url = http.api.mediasChannel + channelId + '?page=' + 1 + '&size=' + 4;
        var that = this;
        myHttps({
            url: url,
            method: "GET",
        }).then(res => {
            // console.log(res)
            if (res.code == 1) {
                // for (var i = 0; i < res.data.content.length; i++) {
                //     if (res.data.content[i].nick.length > 4) {
                //         var channelListNick = res.data.content[i].nick.split('')
                //         channelListNick = channelListNick[0] + channelListNick[1] + channelListNick[2] + channelListNick[3]
                //     }else {
                //         channelListNick = res.data.content[i].nick
                //     }
                //     // console.log(channelListNick)
                //     res.data.content[i].names = channelListNick
                    
                //     this.data.channelList.push(res.data.content[i])
                // }
                that.setData({
                    channelList: res.data.content
                });
                // console.log(this.data.channelList)
            }
        }).catch(err => {})
    },
    // 跳转到媒体主页
    goMediaHome (e) {
        // console.log(e)
        let id = e.currentTarget.dataset.id
        wx.navigateTo({
            url: '../mediaHome/mediaHome?id='+id,
            success: function(res) {},
            fail: function(res) {},
            complete: function(res) {},
        })
    },
    onShow(){
        this.findNav(); //进入find请求findnav
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        this.setData({
            nologin: wx.getStorageSync('no_login'),
            first: wx.getStorageSync('first'),
            userId: wx.getStorageSync('userId'),
            domain: domain.domain
        })
        //判断是否 授权登录过 
        if (this.data.nologin == 'yes') { //没有登陆过
            this.setData({
                first: true,
            })
        }
        // 获取屏幕宽高
        var that = this;
        //  高度自适应
        wx.getSystemInfo({
            success: function (res) {
                var clientHeight = res.windowHeight,
                    clientWidth = res.windowWidth,
                    rpxR = 750 / clientWidth;
                var calc = clientHeight * rpxR - 180;
                // console.log(calc)
                that.setData({
                    winHeight: calc
                });
            }
        });
        // this.findNav(); //进入find请求findnav
        this.getMessage(this.data.size, this.data.page); //首次进入页面需要请求
        this.mediasChannel(this.data.channelId);// 获取媒体列表接口
    },
    scroll: function (event) {
        this.setData({
            scrollTop: event.detail.scrollTop
        });
    }, 
    // 下拉刷新
    refresh: function (e) {
         console.log('下拉刷新')
        var that = this;
        setTimeout(function () {
            var date = new Date();
            that.setData({
                // channelList: [],
                // findList: [],
                size: 10,
                page: 1,
                scrollTop: 0,
                refreshTime: date.toLocaleTimeString(),
                // hideHeader: false,
                // hiddenLoading:false
            })
            let id = that.data.ids
            // console.log(id)
            that.setData({
                ids: id,
            });
            // 走搜索接口
            if (id == 0) {
                that.getMessage(that.data.size, that.data.page,'xiala'); //首次进入页面需要请求   
                that.mediasChannel(0)
            } else {
                that.mediasChannel(id)
                that.channelList(id,'Isxiala');//主题列表
            }
        }, 800);
    },
    // 上拉加载更多
    loadMore: function () {
        var that = this;
        // 当前页是最后一页
        // if (that.data.currentPage == that.data.allPages) {
        //     that.setData({
        //         loadMoreData: '已经到顶'
        //     })
        //     return;
        // }
        setTimeout(function () {
            // console.log('上拉加载更多');
            let id = that.data.ids
            that.setData({
                // hiddenLoading: false,
                ids: id,
            })
            // 走搜索接口
            if (id == 0) {
                that.setData({
                    size: 10,
                    page: that.data.page + 1,
                })
                that.getMessage(that.data.size, that.data.page); //首次进入页面需要请求   
                // that.mediasChannel(0) 
            } else {
                // that.mediasChannel(id)
                that.setData({
                    size: 10,
                    page: that.data.page + 1,
                })
                that.channelList(id);//主题列表
            }
        }, 300);
    },
    // 点击确定  弹出授权登陆
    goLogin() {
        // 调用微信登陆接口 
        login()
        this.setData({
            first: false,
            userInfo: wx.getStorageSync('userInfo'),
        })
    },
    // 点击每一项 跳到主题主页
    goTheme(e) {
        // wx.setStorageSync('themeId', e.currentTarget.dataset.id)
        var id = e.currentTarget.dataset.id
        wx.navigateTo({
            url: '../themeHome/themeHome?id=' + id
        });
    },
    // 点击跳转到search
    gosearch() {
        wx.navigateTo({
            url: '../search/search'
        });
    },
    // 点击小叉  关闭
    close() {
        this.setData({
            show: false
        });
    },
    // 点击小笔 跳转到创建主题页面
    goCreateTheme() {
        //清除之前得主题缓存数据
        wx.removeStorage({
            key: 'apply',
        })
        wx.removeStorage({
            key: 'title',
        })
        wx.removeStorage({
            key: 'wgList',
        })
        wx.removeStorage({
            key: 'mediaData',
        })
        wx.removeStorage({
            key: 'avatar',
        })
        // this.users()
        wx.navigateTo({
            url: '../createTheme/createTheme'
        });
    },
    //添加关注 关注主题接口
    addgz(e) {
        this.setData({
            hiddenLoading: false
        })
        let that = this
        var id = e.currentTarget.dataset.add;
        let index = e.currentTarget.dataset.index;
        // console.log(e)
        // 走关注的接口 
        let url = http.api.followtheme + id + '/fav';
        myHttps({
            url: url,
            method: "POST",
        }).then(res => {
            // 关注成功后 改变状态
            if (res.code == 1) {
                this.data.findList[index].isFav = true,
                this.data.findList[index].fav_count = this.data.findList[index].fav_count+1 ,
                that.setData({
                    findList: this.data.findList,
                    hiddenLoading: true
                })
            }
        }).catch(err => { })
    },
    // 取消关注
    canclegz(e) {
        let that = this
        var id = e.currentTarget.dataset.id;
        let index = e.currentTarget.dataset.index;
        // 走取消关注的接口 
        let url = http.api.delFollow + id + '/fav';
        myHttps({
            url: url,
            method: "DELETE"
        }).then(res => {
            if (res.code == 1) {
                // 取消关注后 改变状态 
                this.data.findList[index].isFav = false,
                this.data.findList[index].fav_count = this.data.findList[index].fav_count - 1,
                that.setData({
                    findList: this.data.findList,
                    hiddenLoading: true
                })
            }
        }).catch(err => { })
    },
    //点击回车请求
    keywordSearch(e) {
        // console.log(e.detail.value)
        this.setData({
            searchKeyword: e.detail.value
        })
    },
    // 获取发现页面头部的nav
    findNav() {
        let url = http.api.myChannel + this.data.userId + '/channels';
        myHttps({
            url: url,
            method: "GET",
        }).then(res => {
            if (res.code == 1) {
                let nav = [];
                let cuijian = {
                    title: '全部',
                    id: 0
                }
                let content = res.data.content
                nav.push(cuijian)
                // console.log(nav)
                for (var i = 0; i < content.length; i++) {
                    nav.push(content[i])
                }
                // console.log(nav)  
                this.setData({
                    findNav: nav,
                })
                // console.log(this.data.findNav)
            }
        }).catch(err => { })
    },
    // go channel选择频道
    channel(e) {
        let froms = e.currentTarget.dataset.from;//判断从发现页面进来的
        wx.navigateTo({
            url: '../../pages/channel/channel?froms=' + 'find',
            success: function (res) { },
            fail: function (res) { },
            complete: function (res) { },
        })
    },
})